import 'package:get/get.dart';
import 'package:share_plus/share_plus.dart';
import 'package:intl/intl.dart' show DateFormat;
import '../../../data/models/wiki_config.dart';
import '../../../utils/storage_service.dart';
import '../../../config/app_constants.dart';
import '../../main_screen/controllers/main_screen_controller.dart';
import '../../favorites/controllers/favorites_controller.dart';

class HistoryController extends GetxController {
  final StorageService _storageService = Get.find<StorageService>();
  
  // 响应式状态
  final RxList<WikiItem> history = <WikiItem>[].obs;
  final RxList<WikiItem> filteredHistory = <WikiItem>[].obs;
  final RxBool isLoading = false.obs;
  final RxString searchQuery = ''.obs;
  
  @override
  void onInit() {
    super.onInit();
    loadHistory();
  }
  
  /// 加载历史记录
  Future<void> loadHistory() async {
    try {
      isLoading.value = true;
      final historyData = _storageService.getHistory();
      final historyList = historyData.map((data) => WikiItem.fromJson(data)).toList();
      history.assignAll(historyList);
      filteredHistory.assignAll(historyList);
    } catch (e) {
      Get.snackbar(
        '错误',
        '加载历史记录失败: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
    } finally {
      isLoading.value = false;
    }
  }
  
  /// 添加到历史记录
  Future<void> addToHistory(WikiItem item) async {
    try {
      // 添加访问时间戳
      final itemWithTimestamp = WikiItem(
        id: item.id,
        name: item.name,
        nameEn: item.nameEn,
        nameCn: item.nameCn,
        description: item.description,
        descriptionCn: item.descriptionCn,
        url: item.url,
        urlCn: item.urlCn,
        icon: item.icon,
        category: item.category,
        tags: item.tags,
        isPopular: item.isPopular,
        isOfficial: item.isOfficial,
        language: item.language,
        rating: item.rating,
        lastUpdated: DateTime.now(),
      );
      
      await _storageService.addToHistory(itemWithTimestamp.toJson());
      
      // 移除旧记录（如果存在）
      history.removeWhere((h) => h.id == item.id);
      // 添加到列表开头
      history.insert(0, itemWithTimestamp);
      
      // 限制历史记录数量（最多保留1000条）
      if (history.length > 1000) {
        history.removeRange(1000, history.length);
        await _storageService.clearHistory();
        for (final h in history) {
          await _storageService.addToHistory(h.toJson());
        }
      }
      
      _applyFilter();
    } catch (e) {
      Get.snackbar(
        '错误',
        '添加历史记录失败: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
    }
  }
  
  /// 从历史记录中移除
  Future<void> removeFromHistory(WikiItem item) async {
    try {
      await _storageService.removeFromHistory(item.id);
      history.removeWhere((h) => h.id == item.id);
      _applyFilter();
      
      Get.snackbar(
        '成功',
        AppConstants.msgHistoryRemoved,
        snackPosition: SnackPosition.BOTTOM,
      );
    } catch (e) {
      Get.snackbar(
        '错误',
        '删除历史记录失败: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
    }
  }
  
  /// 清空所有历史记录
  Future<void> clearAllHistory() async {
    try {
      await _storageService.clearHistory();
      history.clear();
      filteredHistory.clear();
      
      Get.snackbar(
        '成功',
        AppConstants.msgHistoryCleared,
        snackPosition: SnackPosition.BOTTOM,
      );
    } catch (e) {
      Get.snackbar(
        '错误',
        '清空历史记录失败: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
    }
  }
  
  /// 搜索历史记录
  void searchHistory(String query) {
    searchQuery.value = query;
    _applyFilter();
  }
  
  /// 应用搜索过滤
  void _applyFilter() {
    if (searchQuery.value.isEmpty) {
      filteredHistory.assignAll(history);
    } else {
      final lowerQuery = searchQuery.value.toLowerCase();
      final filtered = history.where((item) {
        return item.name.toLowerCase().contains(lowerQuery) ||
               item.nameEn.toLowerCase().contains(lowerQuery) ||
               item.category.toLowerCase().contains(lowerQuery) ||
               item.description.toLowerCase().contains(lowerQuery);
      }).toList();
      filteredHistory.assignAll(filtered);
    }
  }
  
  /// 清除搜索
  void clearSearch() {
    searchQuery.value = '';
    _applyFilter();
  }
  
  /// 打开历史记录项目
  void openHistoryItem(WikiItem item) {
    try {
      // 获取主屏幕控制器
      final mainController = Get.find<MainScreenController>();
      
      // 重新添加到历史记录（更新访问时间）
      addToHistory(item);
      
      // 构建URL并导航
      final url = _buildWikiUrl(item);
      mainController.currentWikiUrl.value = url;
      
      // 返回主屏幕
      Get.back();
      
      Get.snackbar(
        '打开Wiki',
        '正在加载 ${item.name}',
        snackPosition: SnackPosition.BOTTOM,
        duration: const Duration(seconds: 2),
      );
    } catch (e) {
      Get.snackbar(
        '错误',
        '打开Wiki失败: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
    }
  }
  
  /// 添加到收藏
  Future<void> addToFavorites(WikiItem item) async {
    try {
      final favoritesController = Get.find<FavoritesController>();
      await favoritesController.addToFavorites(item);
    } catch (e) {
      // 如果收藏控制器不存在，直接使用存储服务
      try {
        await _storageService.addToFavorites(item.id);
        Get.snackbar(
          '成功',
          AppConstants.msgFavoriteAdded,
          snackPosition: SnackPosition.BOTTOM,
        );
      } catch (storageError) {
        Get.snackbar(
          '错误',
          '添加收藏失败: $storageError',
          snackPosition: SnackPosition.BOTTOM,
        );
      }
    }
  }
  
  /// 分享历史记录项目
  Future<void> shareHistoryItem(WikiItem item) async {
    try {
      final url = _buildWikiUrl(item);
      final shareText = '${item.name}\n${item.nameEn.isNotEmpty ? '${item.nameEn}\n' : ''}$url';
      
      await Share.share(
        shareText,
        subject: '分享Wiki: ${item.name}',
      );
    } catch (e) {
      Get.snackbar(
        '错误',
        '分享失败: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
    }
  }
  
  /// 构建Wiki URL
  String _buildWikiUrl(WikiItem item) {
    if (item.url.isNotEmpty) {
      return item.url;
    }
    
    // 如果没有直接URL，构建搜索URL
    const baseUrl = 'https://wiki.example.com';
    final searchTerm = Uri.encodeComponent(item.name);
    return '$baseUrl/wiki/Special:Search?search=$searchTerm';
  }
  
  /// 获取访问时间显示文本
  String getVisitTime(WikiItem item) {
    if (item.visitTime == null) {
      return '未知时间';
    }
    
    final now = DateTime.now();
    final visitTime = item.visitTime!;
    final difference = now.difference(visitTime);
    
    if (difference.inMinutes < 1) {
      return '刚刚';
    } else if (difference.inMinutes < 60) {
      return '${difference.inMinutes}分钟前';
    } else if (difference.inHours < 24) {
      return '${difference.inHours}小时前';
    } else if (difference.inDays < 7) {
      return '${difference.inDays}天前';
    } else {
      return DateFormat('MM-dd HH:mm').format(visitTime);
    }
  }
  
  /// 按日期分组历史记录
  Map<String, List<WikiItem>> getGroupedHistory() {
    final Map<String, List<WikiItem>> grouped = {};
    final now = DateTime.now();
    
    for (final item in filteredHistory) {
      String dateKey;
      
      if (item.visitTime == null) {
        dateKey = '未知日期';
      } else {
        final visitTime = item.visitTime!;
        final difference = now.difference(visitTime);
        
        if (difference.inDays == 0) {
          dateKey = '今天';
        } else if (difference.inDays == 1) {
          dateKey = '昨天';
        } else if (difference.inDays < 7) {
          dateKey = '${difference.inDays}天前';
        } else {
          dateKey = DateFormat('yyyy年MM月dd日').format(visitTime);
        }
      }
      
      grouped.putIfAbsent(dateKey, () => []);
      grouped[dateKey]!.add(item);
    }
    
    // 按日期排序（最新的在前）
    final sortedEntries = grouped.entries.toList();
    sortedEntries.sort((a, b) {
      // 特殊处理今天、昨天等
      if (a.key == '今天') return -1;
      if (b.key == '今天') return 1;
      if (a.key == '昨天') return -1;
      if (b.key == '昨天') return 1;
      
      // 其他按字符串比较（可能需要更复杂的日期比较）
      return b.key.compareTo(a.key);
    });
    
    return Map.fromEntries(sortedEntries);
  }
  
  /// 获取历史记录统计信息
  Map<String, dynamic> getHistoryStats() {
    final stats = <String, dynamic>{};
    final categoryCount = <String, int>{};
    
    for (final item in history) {
      final category = item.category.isEmpty ? '其他' : item.category;
      categoryCount[category] = (categoryCount[category] ?? 0) + 1;
    }
    
    stats['totalCount'] = history.length;
    stats['categoryCount'] = categoryCount;
    stats['todayCount'] = history.where((item) {
      if (item.visitTime == null) return false;
      final now = DateTime.now();
      final visitTime = item.visitTime!;
      return now.difference(visitTime).inDays == 0;
    }).length;
    
    return stats;
  }
  
  /// 导出历史记录
  Future<void> exportHistory() async {
    try {
      final historyList = history.map((item) => {
        'id': item.id,
        'name': item.name,
        'nameEn': item.nameEn,
        'category': item.category,
        'description': item.description,
        'url': item.url,
        'tags': item.tags,
        'visitTime': item.visitTime?.toIso8601String(),
      }).toList();
      
      final exportData = {
        'exportTime': DateTime.now().toIso8601String(),
        'totalCount': history.length,
        'history': historyList,
      };
      
      await Share.share(
        'My Wiki History Export\n\n${exportData.toString()}',
        subject: 'Wiki浏览历史导出',
      );
      
      Get.snackbar(
        '成功',
        '历史记录已导出',
        snackPosition: SnackPosition.BOTTOM,
      );
    } catch (e) {
      Get.snackbar(
        '错误',
        '导出失败: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
    }
  }
  
  /// 刷新历史记录
  Future<void> refreshHistory() async {
    await loadHistory();
  }
}